<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js"></script>
  </head>
  <body>
    <button onclick="copy()">复制鼠标选中的文字</button>
    <p>12314214</p>
    <button onclick="copyFn()" class="clickboard">clipboard.js实现复制</button>
    <button onclick="copyFnNav('复制文字')" class="clickboardNav">navigator.clipboard.writeText实现复制</button>
    <script>
      // 复制鼠标选中的文字 不实用
      function copy() {
        document.execCommand("copy"); // 复制
      }
      function copyFn() {
        //复制方法
        var clickBoard = new ClipboardJS(".clickboard", {
          text: () => {
            let innerText = document.querySelector(".clickboard");
            return innerText.innerHTML;
          },
        });
        //复制成功
        clickBoard.on("success", (e) => {
          console.log(`已复制:${e.text}`);
        });
        //复制失败
        clickBoard.on("error", (e) => {
          console.log("error", e);
        });
      }
      function copyFnNav(val){
        // let innerText = document.querySelector(".clickboardNav");
        // navigator.clipboard.writeText(innerText.innerHTML);
        // 或
        navigator.clipboard.writeText(val);
      }
    </script>
  </body>
</html>
